var PROVINCIALDEFAULTOPTION="<option value='0'>--请选择省级公司--</option>";
var MUNICIPALDEFAULTOPTION="<option value='0'>--请选择市级公司--</option>";
var CENTERDEAFAULTOPIONT="<option value='0'>--请选择理赔中心--</option>";
var HOME_OFFICE_LEVEL=1;
var PROVINCIAL_LEVEL=2;
var MUNIPITAL_LEVEL=3;
var CLAIM_CENTER_LEVEL=4;
var ALERT_MESSAGE_DONT_SELECT_COMPANY="请选择公司再做查询！";
var ROLE_ID_SEPARATOR=":";

$(document).ready(function() {	
	 initDropDownSelectMenu();	
	 initQueryCondition();
	 initSpecialCompanyRadioButton();
	
});

function initSpecialCompanyRadioButton(){
	var sepcialCompanyRadioButtonValue = $('input[name=queryCompanyCondition][checked]').val();
	if(sepcialCompanyRadioButtonValue==1){
		$("#specialCompanyTr").css("display","none");
	}
}

function hideAndShowDropDownMenu(value){
	if(value==1){
		//hide drop down menu
		$("#specialCompanyTr").css("display","none");
		
	}else{
		//show drop down menu
		$("#specialCompanyTr").css("display","");
	
	}
}

function initQueryCondition(){
	var pageParmStr=$("#pageParm").val();
	var pageParmObj=evalJSON(pageParmStr);	
	var account=pageParmObj.account;
	var userName=pageParmObj.userName;
	$("#user_account").val(account);
	$("#user_userName").val(userName);
	var roleIds=pageParmObj.roleIds;
	//alert(roleIds);
	if(roleIds!=""){
		var roleS=roleIds.split(ROLE_ID_SEPARATOR);
		for(var i=0;i<roleS.length;i++){
			//alert($("#role_"+roleS[i]).val());
			$("#role_"+roleS[i]).attr("checked",true);	
		}
	}
}

function initDropDownSelectMenu(){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);	
	var userCompanyLevel=menuObj.userCompanyLevel;	
	if(userCompanyLevel==PROVINCIAL_LEVEL){
		disableSelectMenu("#provincial");
	}else if(userCompanyLevel==MUNIPITAL_LEVEL){
		disableSelectMenu("#provincial");
		disableSelectMenu("#municipal");
	}else if(userCompanyLevel==CLAIM_CENTER_LEVEL){
		disableSelectMenu("#provincial");
		disableSelectMenu("#municipal");
		disableSelectMenu("#center");
	}
}

function queryUser(){
	
	//execute company menu parameter
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);
	//able all
	ableAllSelectMenu();
	//get company value
	var provincialCompanyValue=$("#provincial").val();
	var municipalCompanyValue=$("#municipal").val();
	var centerCompanyValue=$("#center").val();
	var level=0;//query in the scope of all company
	var selectedCompanyId="-1";//default : query in the scope of all company
	var sepcialCompanyRadioButtonValue = $('input[name=queryCompanyCondition][checked]').val();
	if(sepcialCompanyRadioButtonValue==2){ // special company radio button is selected
		//provincial
		if(provincialCompanyValue==0){
			/*alert(ALERT_MESSAGE_DONT_SELECT_COMPANY);
			return false;*/
			level=parseInt(HOME_OFFICE_LEVEL);
			selectedCompanyId=menuObj.userCompanyId;
		}
		//municipal
		else if(municipalCompanyValue==0){
			level=parseInt(PROVINCIAL_LEVEL);
			selectedCompanyId=provincialCompanyValue;
		}
		//center
		else if(centerCompanyValue==0){
			level=parseInt(MUNIPITAL_LEVEL);
			selectedCompanyId=municipalCompanyValue;
		}else{
			level=parseInt(CLAIM_CENTER_LEVEL);
			selectedCompanyId=centerCompanyValue;
		}
	}
	
	//set value to json object and convert to string from object	
	menuObj.currentSelectedCompanyId=selectedCompanyId;
	menuObj.currentSelectedCompanyLevel=level;
	//set json string to hidden string
	var jsonStr=evalJSONString(menuObj);
	//clear page number
	$("#_p_currentPage_id").val("");
	$("#_p_totalPage_id").val("");	
	$("#menuLayOut").val(jsonStr);	
	//execute user role parameter
	var pageParmStr=$("#pageParm").val();
	var pageObj=evalJSON(pageParmStr);
	//set attribute
	var userName=$("#user_userName").val().trim();
	var account=$("#user_account").val().trim();
	var companyId=selectedCompanyId;
	var checkbox=$('input[name=roleName_query][checked]');
	
	var roleIdList="";
	$.each(checkbox,function(i){		
		var roleId=checkbox.eq(i).val();
		roleIdList+=roleId;
		roleIdList+=ROLE_ID_SEPARATOR;	
	});
	roleIdList=roleIdList.substring(0, roleIdList.length-1);
	pageObj.specialQueryCompanyType=sepcialCompanyRadioButtonValue;	
	pageObj.account=account;
	pageObj.userName=userName;	
	pageObj.companyId=companyId;
	pageObj.roleIds=roleIdList;
	var pageParmString=evalJSONString(pageObj);
	$("#pageParm").val(pageParmString);	

	submitActionByMethod('#form1','queryUser');
	
}

function submitActionByMethod(formId,methodName){
	
	var action = $(formId).attr("action");
	$(formId).attr("action",action+"?method:"+methodName);
	
    $(formId).submit();
   
}


String.prototype.trim = function()
{
	var reExtraSpace = /^\s*(.*?)\s+$/;
	return this.replace(reExtraSpace,"$1");
};

function reloadDivDialog(id,width,minWidth){
	 $(id).dialog({
	        autoOpen: false,
	        modal: true,                  // 是否使用模式窗口，模式窗口打开后，页面其他元素将不能点击，直到关闭模式窗口。
	        closeOnEscape: true,           // true: 点击键盘ESC键关闭dialog
	        width: width, minWidth: minWidth, 	       
	        resizable: true,
	        draggable: false
	    });
}


//reset municipal menu by ajax
function getMunicipal(){
	 var selectedProvincialCompany=$("#provincial").val();
	 if(selectedProvincialCompany==0||selectedProvincialCompany==-1){
	   	clearDropDownSelectMenu('#center',CENTERDEAFAULTOPIONT);
		clearDropDownSelectMenu('#municipal',MUNICIPALDEFAULTOPTION);
		return;
	 }else{
		clearDropDownSelectMenu('#center',CENTERDEAFAULTOPIONT);
    addOptionByAjax('../admin/ajaxGetMunicipalList.action',selectedProvincialCompany,'#municipal',MUNICIPALDEFAULTOPTION);
	
	 }   
}

//reset center menu by ajax
function getCenter(){		
	 var selectedMunicipalCompany=$("#municipal").val();	 
	 if(selectedMunicipalCompany==0||selectedMunicipalCompany==-1){
 	   clearDropDownSelectMenu('#center',CENTERDEAFAULTOPIONT);
 	   return;
 }else{ 
	  addOptionByAjax('../admin/ajaxGetClaimCenter.action',selectedMunicipalCompany,'#center',CENTERDEAFAULTOPIONT);
	} 
}

function addOptionByAjax(url,selectedCompanyId,dropDownMenuId,option){
	 $.ajax({
        url: url,
        data: 'companyId='+selectedCompanyId,
        dataType: "json",
        cache: false,
        success: function(json){ 
         var companys = eval(json);
	   	     clearDropDownSelectMenu(dropDownMenuId,option);	   		   	    
            $.each(companys,function(i, company){	
         	    $(dropDownMenuId).append("<option value='"+company.companyId+"'>"+company.companyName+"</option>");
           });  
           
       },
	       error: function(XMLHttpRequest, textStatus, errorThrown) {
    	   alert(textStatus);
       }
    }); 
}

function showAddUser(){
	$("#UpdateUser").html("");
	//get html by ajax
	var url="user/ajaxInitializeAddUser.action";
	//var params={"userCompanyId":userCompanyId, "userCompanyLevel":userCompanyLevel};
	var params="";
	var divId="#AddUser";
	setValueToDivByAjax(url,params,divId);
	//

	openDivDialog('#AddUser');
	
	//SPECIAL CASE: if is super admin, set radio[总公司] enabled and selected
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);
	if (menuObj.superAdmin == true) {
		$("#homeOfficeRadioButton").attr("disabled", false);
		$("#homeOfficeRadioButton").attr("checked", true);
		hideAllCompanySelectedMenu();
		initRoleCheckBoxButton();
		
	}
	
}

function showUserUpdate(userId,companyId,companyLevel){
	$("#AddUser").html("");
	//get html by ajax
	var url="user/ajaxInitializeUpdateUser.action";
	//var params={"userCompanyId":userCompanyId, "userCompanyLevel":userCompanyLevel};
	var params={"userId":userId,"companyId":companyId,"companyLevel":companyLevel};
	var divId="#UpdateUser";
	setValueToDivByAjax(url,params,divId);
	//

	openDivDialog('#UpdateUser');
	
	//SPECIAL CASE: if is super admin, set radio[总公司] enabled
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);
	if (menuObj.superAdmin == true) {
		$("#homeOfficeRadioButton_update").attr("disabled", false);
	}
}

function showUserDelete(account){
	//can't delete self
	var pageParmStr=$("#pageParm").val();
	var pageParmObj=evalJSON(pageParmStr);	
	var adminAccount=pageParmObj.adminAccount;
	
	if(account==adminAccount){
		
		showAlertDialogue('不能删除自己','');
		return false;
	}	
	showConfirmDialogue('确定删除吗',deleteUser,account);
}


function deleteUser(account){
	$.ajax({
        type:"POST",
        async:false,
        url:"user/ajaxUserDelete.action",
        data:{"account":account},
        success:function(data2) {
        	//hideTip();
        	if(data2==0){
    			alert('删除失败！');
    		}else{
    		//foward to new page
    			showAlertDialogue('删除成功',forwardToNewPage,'userExcutePagination.action');
    			//clear page number
    			$("#_p_currentPage_id").val("");
    			$("#_p_totalPage_id").val("");	
    		}
          }
    });	
}

function forwardToNewPage(url){
	$("#form1").attr("action",url);
    $("#form1").submit();
}

function openDivDialog(id){
	 reloadDivDialog('#UpdateUser',800,800);
	 reloadDivDialog('#AddUser',800,800); 
	if($(id).dialog( 'isOpen' )){	
		$(id).dialog( 'close' );
	}else{
		$(id).dialog( 'open' );
	}	

}

function setValueToDivByAjax(url,params,divId){
	
	//show tip
	//showTip();
	
		$.ajax({
	        type:"POST",
	        async:false,
	        url:url,
	        data:params,
	        success:function(data) {
			//close tip
				//hideTip();	               
	            $(divId).html("");
	    		$(divId).html(data);
	              
	          }
	    });
	}
//clear drop down select menu
function clearDropDownSelectMenu(id,option){
	$(id+' option').remove();
	$(id).append(option);
}

//add option to select menu
function addSubOptionByPostion(id,option){
	$(id).append(option);
}
//convert json string to json object
function evalJSON(strJson){
	return jQuery.parseJSON(strJson);
}
//disable select menu by id
function disableSelectMenu(id){
	$(id).attr("disabled",true);
}

function ableAllSelectMenu(){
	$("#provincial").attr("disabled",false);
	$("#municipal").attr("disabled",false);
	$("#center").attr("disabled",false);
}

//convert json object to json string
function evalJSONString(objJson){
	return $.toJSON(objJson);
}

function showParent(id){
	$(id).dialog( 'close' );
}

function resetQuery(provincialId,municipalId,centerId){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);	
	var userCompanyLevel=menuObj.userCompanyLevel;	
	
	if ($(municipalId).is(':visible'))
		resetLevel(userCompanyLevel,provincialId,municipalId,centerId);
	
	$("#user_account").val('');	
	$("#user_userName").val('');
	$("#role_1").attr("checked",false);
	$("#role_2").attr("checked",false);
	$("#role_3").attr("checked",false);
	$("#role_4").attr("checked",false);
	$("#role_5").attr("checked",false);
	$("#role_6").attr("checked",false);
	$("#queryCompanyCondition_id1").attr("checked",true);
	$("#queryCompanyCondition_id2").attr("checked", false);
	$("#specialCompanyTr").hide();
	
}

function resetLevel(level,provincialId,municipalId,centerId){
	if(level==1){
		$(provincialId).val(0);
		$(municipalId).html(MUNICIPALDEFAULTOPTION);
		$(municipalId).val(0);
		$(centerId).html(CENTERDEAFAULTOPIONT);
		$(centerId).val(0);
	} else if (level==2){
		$(municipalId).val(0);
		$(centerId).html(CENTERDEAFAULTOPIONT);
		$(centerId).val(0);
	} else if (level==3){
		$(centerId).val(0);
	}
}

function startLoading() {
    $('#CA_loading').show();
}

function endLoading() {
    $('#CA_loading').hide();
}

